<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin\AdminUser;
use App\Models\Home\Comment;
use App\Models\Home\Topic;
use App\Models\Home\User;
use App\Models\Home\Weibo;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;

class IndexController extends Controller
{
    //后台首页统计数据
    public function index()
    {
        $data['weibo'] = Weibo::all()->count();
        $data['topic'] = Topic::all()->count();
        $data['comment'] = Comment::all()->count();
        $data['user'] = User::all()->count();
        return view('admin/index', ['data' => $data]);
    }

    //登录页面
    public function login(Request $request)
    {
        //判断请求方式
        //post请求
        if ($request->isMethod('post')) {
            //进行格式验证
            //设置格式验证规则
            $rules = ['username' => 'required',
                'password' => 'required',
                'captcha' => 'required|captcha'];
            //设置格式错误信息
            $msg = ['username.required' => '用户名不能为空',
                'password.required' => '密码不能为空',
                'captcha.required' => '验证码不能为空',
                'captcha.captcha' => '验证码不正确'];
            //进行格式验证
            $validator = Validator::make($request->all(), $rules, $msg);
            if ($validator->fails()) {
                return redirect('admin/login')->withErrors($validator)->withInput();
            }
            //格式验证通过后进行格式验证
            //获取传递过来的数据
            $username = $request->username;
            //禁止用户登录
            if (AdminUser::where('name', $username)==null){
                return back()->with('loginFails', '用户名密码不匹配');
            }

            if(AdminUser::where('name', $username)->first()->is_allowed==0){
                return back()->with('loginFails', '用户禁止登陆');
            }
            //判断密码是否正确
            $password = $request->password;
            //密码Hash验证，取出该user对应的数据库密码
            $res = AdminUser::where('name', $username)->get()->first();
            $password_db = $res->password;
            if (!Hash::check($password, $password_db)) {
                return back()->with('loginFails', '用户名密码不匹配');
            }
            //登录有记录表示成功，将登陆信息保存到session中
            Session::put('admin_user.id', $res->id);
            Session::put('admin_user.name', $res->name);
            Session::save();
            return redirect('/admin');
//            return '123';
        }
        //其他请求方式
        return view('/admin/login');
    }

    //后台退出
    public function logout(Request $request)
    {
        //清空用户信息
        Session::forget('admin_user');
        return redirect('/admin/login');
    }
}